const express = require('express');
const app = express();
const request = require('request');
const { Buffer } = require('buffer');
const http = require('http');
const https = require('https');
const fs = require('fs');
const cors = require('cors');
    
// 代理服务器端口
const port = 3000;

// 启用 CORS 中间件
app.use(cors());

function downloadImage(url, filePath='./downloaded-image.jpg') {
    console.log("%c Line:17 🍅 url", "color:#93c0a4", url);
    return new Promise((resolve, reject) => {
       
        const protocol = url.startsWith('https')? https : http;
        const file = fs.createWriteStream(filePath);

        protocol.get(url, (response) => {
            if (response.statusCode!== 200) {
                console.error(`请求失败，状态码：${response.statusCode}`);
                return;
            }

            response.pipe(file);

            file.on('finish', () => {
                file.close();
                resolve();
            });

            file.on('error', (err) => {
                fs.unlink(filePath, () => {});
                console.error(`保存文件时出错：${err.message}`);
                reject(err);
            });
        }).on('error', (err) => {
            console.error(`请求出错：${err.message}`);
            reject(err);
        }); 
    })
}

// 使用示例
// const imageUrl = 'https://song.gushiwen.cn/authorImg/fanzhongyan.jpg';
// downloadImage(imageUrl);

// 代理图片请求
app.get('/proxy-image', async (req, res) => {
    const imageUrl = req.query.url;
    await downloadImage(imageUrl);
    // 读取图片文件
    const imagePath = './downloaded-image.jpg'; // 替换为实际的图片路径
    const imageData = fs.readFileSync(imagePath);

    // 将图片数据转换为 Base64 编码
    const dataUri = `data:image/jpeg;base64,${imageData.toString('base64')}`;
    //删除照片
    fs.unlink(imagePath, () => {});
    // 返回 Base64 数据
    res.send(dataUri);
});

app.listen(port, () => {
    console.log(`代理服务器在端口 ${port} 上运行`);
});